"""
AI工具集数据模型
"""

from datetime import datetime
from enum import Enum
from typing import List, Optional, Any

from pydantic import BaseModel, Field, field_validator, ConfigDict, model_serializer


class ToolsStatus(int, Enum):
    """工具集状态枚举"""
    DISABLED = 0  # 禁用
    ENABLED = 1  # 可用

    @classmethod
    def validate_status(cls, value):
        """验证并转换status值"""
        if isinstance(value, int):
            if value in [0, 1]:
                return value
            else:
                raise ValueError(f"无效的状态值: {value}，必须是 0, 1 中的一个")
        elif isinstance(value, str):
            try:
                int_value = int(value)
                if int_value in [0, 1]:
                    return int_value
                else:
                    raise ValueError(f"无效的状态值: {value}，必须是 0, 1 中的一个")
            except ValueError:
                raise ValueError(f"无效的状态值: {value}，必须是 0, 1 中的一个")
        elif isinstance(value, bool):
            return 1 if value else 0
        else:
            raise ValueError(f"状态值必须是整数或布尔值，当前类型: {type(value)}")


class ToolParameter(BaseModel):
    """工具参数模型"""
    param_name: str = Field(..., description="参数名称")
    param_type: str = Field(..., description="参数类型，如integer、float、string、boolean等")
    description: str = Field(default="", description="参数描述")
    default_value: Any = Field(None, description="默认值")
    is_required: bool = Field(default=False, description="是否必需参数")


class AIWebTools(BaseModel):
    """AI工具集实体类"""
    model_config = ConfigDict(from_attributes=True)

    id: Optional[int] = Field(None, description="主键ID")
    category_name: str = Field(..., max_length=100, description="工具类名称")
    category_code: str = Field(..., max_length=50, description="工具类代码，唯一标识")
    description: Optional[str] = Field(None, description="工具类介绍")
    is_enabled: int = Field(default=1, description="工具类是否可用(1=可用,0=禁用)")
    created_at: Optional[datetime] = Field(None, description="创建时间")
    updated_at: Optional[datetime] = Field(None, description="更新时间")

    @model_serializer
    def serialize_model(self):
        """自定义序列化器"""
        data = self.__dict__.copy()
        if 'created_at' in data and data['created_at']:
            data['created_at'] = data['created_at'].isoformat()
        if 'updated_at' in data and data['updated_at']:
            data['updated_at'] = data['updated_at'].isoformat()
        return data

    @field_validator('is_enabled', mode='before')
    @classmethod
    def validate_is_enabled(cls, v):
        """验证is_enabled字段"""
        return ToolsStatus.validate_status(v)

    @field_validator('category_name')
    @classmethod
    def validate_category_name(cls, v):
        """验证工具类名称"""
        if not v or not v.strip():
            raise ValueError('工具类名称不能为空')
        if len(v.strip()) > 100:
            raise ValueError('工具类名称长度不能超过100个字符')
        return v.strip()


class AIWebToolsCreate(BaseModel):
    """创建工具集请求模型"""
    category_name: str = Field(..., max_length=100, description="工具类名称")
    description: Optional[str] = Field(None, description="工具类介绍")
    is_enabled: int = Field(default=1, description="工具类是否可用(1=可用,0=禁用)")

    @field_validator('is_enabled', mode='before')
    @classmethod
    def validate_is_enabled(cls, v):
        """验证is_enabled字段"""
        return ToolsStatus.validate_status(v)

    @field_validator('category_name')
    @classmethod
    def validate_category_name(cls, v):
        """验证工具类名称"""
        if not v or not v.strip():
            raise ValueError('工具类名称不能为空')
        if len(v.strip()) > 100:
            raise ValueError('工具类名称长度不能超过100个字符')
        return v.strip()


class AIWebToolsUpdate(BaseModel):
    """更新工具集请求模型"""
    category_name: Optional[str] = Field(None, max_length=100, description="工具类名称")
    description: Optional[str] = Field(None, description="工具类介绍")
    is_enabled: Optional[int] = Field(None, description="工具类是否可用(1=可用,0=禁用)")

    @field_validator('is_enabled', mode='before')
    @classmethod
    def validate_is_enabled(cls, v):
        """验证is_enabled字段"""
        if v is not None:
            return ToolsStatus.validate_status(v)
        return v

    @field_validator('category_name')
    @classmethod
    def validate_category_name(cls, v):
        """验证工具类名称"""
        if v is not None:
            if not v or not v.strip():
                raise ValueError('工具类名称不能为空')
            if len(v.strip()) > 100:
                raise ValueError('工具类名称长度不能超过100个字符')
            return v.strip()
        return v


class AIWebToolsResponse(BaseModel):
    """工具集响应模型"""
    model_config = ConfigDict(from_attributes=True)

    id: int
    category_name: str
    category_code: str
    description: Optional[str]
    is_enabled: int
    created_at: datetime
    updated_at: datetime


class AIWebToolsQueryParams(BaseModel):
    """工具集查询参数"""
    category_name: Optional[str] = Field(None, description="工具类名称模糊查询")
    category_code: Optional[str] = Field(None, description="工具类代码查询")
    is_enabled: Optional[int] = Field(None, description="状态筛选：1-可用，0-禁用")

    @field_validator('is_enabled', mode='before')
    @classmethod
    def validate_is_enabled(cls, v):
        """验证is_enabled字段"""
        if v is not None:
            return ToolsStatus.validate_status(v)
        return v


class AIWebToolsListResponse(BaseModel):
    """工具集列表响应模型"""
    total: int = Field(..., description="总数量")
    items: List[AIWebToolsResponse] = Field(..., description="工具集列表")


class AIWebToolsStatusUpdate(BaseModel):
    """工具集状态更新模型"""
    is_enabled: int = Field(..., description="新状态：1-可用，0-禁用")

    @field_validator('is_enabled', mode='before')
    @classmethod
    def validate_is_enabled(cls, v):
        """验证is_enabled字段"""
        return ToolsStatus.validate_status(v)


class SingleToolModel(BaseModel):
    """单个工具配置模型"""
    id: Optional[int] = Field(None, description="工具ID")
    tool_name: str = Field(..., description="工具名称")
    description: str = Field(default="", description="工具描述")
    is_enabled: bool = Field(default=True, description="是否启用")
    parameters: List[ToolParameter] = Field(default_factory=list, description="工具参数列表")

    @field_validator('tool_name')
    @classmethod
    def validate_tool_name(cls, v):
        """验证工具名称"""
        if not v or not v.strip():
            raise ValueError('工具名称不能为空')
        return v.strip()


class AIWebToolsDetailResponse(BaseModel):
    """工具集详细信息响应模型"""
    model_config = ConfigDict(from_attributes=True)

    id: int
    category_name: str
    category_code: str
    description: Optional[str]
    is_enabled: int
    tools: List[SingleToolModel] = Field(..., description="工具列表")
    created_at: datetime
    updated_at: datetime
